Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
An input string is valid if:
Example 2
Input: s = "()[]{}"
Output: true
class Solution:
def isValid(self, s: str) -> bool:
dic = {
'(' : ')',
'{' : '}',
'[' : ']'
}
stack = []
for i in s:
if i in dic:
stack.append(i)
else:
if not stack:
return False
top = stack.pop()
if dic[top] != i:
return False
return not stack
Time Complexity: O(N)
Space Complexity: O(N)
class Solution:
def isValid(self, s: str) -> bool:
stack = []
for i in s:
if i == '(':
stack.append(')')
elif i == '{':
stack.append('}')
elif i == '[':
stack.append(']')
elif (not stack) or (stack.pop() != i):
return False
return not stack
Time Complexity: O(N)
Space Complexity: O(N)
https://leetcode.com/problems/valid-parentheses/discuss/9178/Short-java-solution
TODO
Time Complexity: O()
Space Complexity: O()